package com.zelin;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.conversions.Bson;

/**
 * Created by WF on 2019/9/19 9:33
 */
public class MongoTest {
    public static void main(String[] args) {
        //1.得到mongodb的客户端
        MongoClient mongoClient = new MongoClient("192.168.25.128");
        //2.根据客户端得到数据库
        MongoDatabase spitdb = mongoClient.getDatabase("spitdb");
        //3.根据数据库得到集合对象
        MongoCollection<Document> spitdbCollection = spitdb.getCollection("spit");
        //4.从集合中查询所有文档
        FindIterable<Document> documents = spitdbCollection.find();
        //5.遍历并打印文档对象
        //printInfo(documents);
        //6.条件查询一
        //6.1)构造查询条件
        //BasicDBObject bson = new BasicDBObject("userid","1013");
        //6.2)开始进行查询
        //FindIterable<Document> docs = spitdbCollection.find(bson);
        //6.3)打印查询结果
        //printInfo(docs);

        //7.条件查询二：查询浏览量大于1000的记录
//        BasicDBObject bson = new BasicDBObject("visits",new BasicDBObject("$gt",1000));
//        FindIterable<Document> docs = spitdbCollection.find(bson);
//        printInfo(docs);

        //8.添加一条记录
        insertOne(spitdbCollection);
    }

    private static void insertOne(MongoCollection<Document> collection) {
        //1.创建要添加的文档对象(代表一条记录)
        Document doc = new Document();
        //2.向此记录的各个字段添加值
        doc.put("content","dddd");
        doc.put("userid","101");
        doc.put("nickname","eeee");
        doc.put("visits",3333);
        doc.put("parentid","2");
        //3.将此记录（文档）添加到集合中
        collection.insertOne(doc);
    }

    private static void printInfo(FindIterable<Document> documents) {
        for (Document document : documents) {
            //5.1）输出文档对象的内容
            Object id = document.get("_id");
            String content = document.getString("content");
            String userid = document.getString("userid");
            String nickname = document.getString("nickname");
            Integer visits = document.getInteger("visits");
            System.out.println("id:" + id);
            System.out.println("content:" + content);
            System.out.println("userid:" + userid);
            System.out.println("nickname:" + nickname);
            System.out.println("visits:" + visits);
            System.out.println("---------------------------------------------");
        }
    }
}
